package cn.big.netty.learn.discard.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by LiJianXin on 2019/5/8 0008.
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {

	/**
	 * 每当从客户端接收到新数据时，都会使用接收到的消息调用此方法
	 *
	 * @param ctx
	 * @param msg 接收到的消息类型为ByteBuf.
	 * @throws Exception
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		//忽略接收到的消息，如果需要放弃此次消息，由于ByteBuf是一个引用计数（ReferenceCounted）对象，必须通过release()方法进行释放
		//((ByteBuf) msg).release();
		ByteBuf in = (ByteBuf) msg;
		try {
			System.out.println(in.toString(CharsetUtil.UTF_8));
		} finally {
			ReferenceCountUtil.release(msg);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		//关闭通道
		ctx.close();
	}
}
